<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, onBeforeUnmount } from 'vue'
import { CurdData, FieldEnum } from '@/api/customerContcat/types'
import { getFieldEnumApi } from '@/api/customerContcat'
import { useI18n } from '@/hooks/web/useI18n'
import useSchema from './hooks/useSchema'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
import DialogChecked from './DialogChecked/index.vue'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
// import useBtnInInput from './hooks/useBtnInInput'
import { Dialog, TableDialog } from '@/components/Dialog'
import { getListApi } from '@/api/customer'
import useTagsInput from './hooks/useTagsInput'
import { useValidator } from '@/hooks/web/useValidator'
import { SelectedItem, useTableDialogStore } from '@/store/modules/tableDialog'

const tableDialogStoreID = 'customerContactWrite'
const itemTitleName = 'cusname'

const tableDialogStore = useTableDialogStore(tableDialogStoreID)

const tableDialogSelectedLimit = 1

// 客户选择弹窗引用
const customerDialogRef = ref()

// 定义组件的 props
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})

const { t } = useI18n()

// 使用表单相关的 hooks
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

// 定义表格对话框的 CRUD 模式
const tableDialogCurdSchema = reactive<CrudSchema[]>([
  {
    field: 'selection',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('customer.index'),
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'cusname',
    label: t('customer.cusname'),
    search: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'phone',
    label: t('customer.phone'),
    form: {
      component: 'Input',
      formItemProps: {}
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'email',
    label: t('customer.email'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'qq',
    label: t('customer.qq'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'wechat',
    label: t('customer.wechat'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  }
])

// 新增标签 start
// 使用表单相关的 hooks
const { formRegister: tagsFormRegister, formMethods: tagsFormMethods } = useForm()
const {
  // setValues,
  getFormData: getTagsFormData,
  getElFormExpose: getTagsElFormExpose
  // setSchema
} = tagsFormMethods

// 使用标签输入相关的 hooks
const { tagsDialogVisible, tagsList, handleTagsButtonClick, removeTag } = useTagsInput()
const tagsObj = {
  tagsList,
  handleTagsButtonClick,
  removeTag
}

// 使用验证相关的 hooks
const { required } = useValidator()

// 定义标签对话框的表单模式
const schemaTagsDialog = reactive<FormSchema[]>([
  {
    field: 'tags',
    label: t('customer.tags'),
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    }
  }
])

// 表单提交处理函数
const formSubmit = async () => {
  const elFormExpose = await getTagsElFormExpose()
  elFormExpose?.validate(async (valid) => {
    if (valid) {
      const formData = await getTagsFormData()
      tagsList.push(formData.tags)
      tagsDialogVisible.value = false
    } else {
      console.log('submit fail')
    }
  })
}
// 新增标签 end

// 使用模式相关的 hooks

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const fieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    fieldEnum.value = res.data
    console.log('fieldEnum', fieldEnum.value)
    const { crudSchemas, handleCustomerSelect } = useSchema(
      undefined,
      fieldEnum.value,
      tableDialogCurdSchema,
      tagsObj,
      tableDialogStoreID,
      customerDialogRef
    )
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      formSchema: newSchemas.formSchema || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })

// 定义表单验证规则
const rules: FormRules = reactive({
  phone: [{ required: true, message: 'Please input your phone number', trigger: 'blur' }],
  email: [
    { required: true, message: 'Please input your email address', trigger: 'blur' },
    { type: 'email', message: '邮箱格式有误', trigger: ['blur', 'change'] }
  ]
})

// 定义一个函数来删除对象中以 '_value' 结尾的属性
const removeValueProperties = (obj) => {
  for (let key in obj) {
    if (key.endsWith('_value')) {
      delete obj[key]
    }
  }
}

// 表单提交处理函数
const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    formData.cusid = tableDialogStore.selectedItems.map((item) => item.id).join(',')
    formData.tags = tagsList.join(',')
    removeValueProperties(formData)
    return formData
  }
}

// 监听当前行的变化
watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const selectedItems = ref<SelectedItem[]>([])
    selectedItems.value = [{ id: currentRow.cusid, title: currentRow.cusid_value }]
    tableDialogStore.selectedItems = selectedItems.value
    setValues(currentRow)
    if (currentRow.tags) {
      let tagsArray = currentRow.tags.split(',')
      tagsArray.forEach((el) => tagsList.push(el))
    }
  },
  {
    deep: true,
    immediate: true
  }
)

// 客户选择回调
const handleCustomerSelect = (val: any[]) => {
  if (!val || !val.length) return

  // 更新 store 中的选中项
  const selectedItems = val.map((item) => ({
    id: item.id,
    title: item.cusname
  }))
  tableDialogStore.setCheckedItems(selectedItems)
}

// 清空 store 数据
onBeforeUnmount(() => {
  tableDialogStore.reset()
})
defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />

  <Dialog width="30%" v-model="tagsDialogVisible" :title="t('customer.tags')">
    <Form
      ref="tagsForm"
      :schema="schemaTagsDialog"
      @register="tagsFormRegister"
      style="margin: 10px"
    />
    <template #footer>
      <BaseButton type="primary" @click="formSubmit">{{ t('dialogDemo.submit') }}</BaseButton>
      <BaseButton @click="tagsDialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>

  <!-- 客户选择弹窗 -->
  <DialogChecked ref="customerDialogRef" @expose-multiple-data="handleCustomerSelect" />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
